<template>
  <div class="app-container">
    <el-form ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类">
        <el-cascader
            :props="categoryProps"
            style="width: 100%"
            v-model="queryCategoryIdList"
            @change="handleCategoryChange"
        />
      </el-form-item>

      <el-form-item label="品牌">
        <el-select
            class="m-2"
            placeholder="选择品牌"
            size="small"
            style="width: 100%"
            v-model="queryParams.brandId"
        >
          <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" id="reset-all" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            @click="handleUpdate"
            :disabled="single"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            @click="handleDelete"
            :disabled="multiple"
        >删除
        </el-button>
      </el-col>
      <right-toolbar v-model:show-search="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据展示表格 -->
    <el-table :data="categoryBrandList" @selection-change="selectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="分类名称" prop="categoryName"/>
      <el-table-column label="品牌名称" prop="brandName"/>
      <el-table-column prop="logo" label="品牌图标" #default="scope">
        <img :src="scope.row.logo" width="50"/>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条组件 -->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />


    <!-- 添加或修改分类品牌对话框 -->
    <el-dialog :title="title" v-model="open" :rules="rules" width="500px" append-to-body>
      <el-form ref="categoryBrandRef" :model="form" label-width="80px">
        <el-form-item label="分类" prop="categoryIdList">
          <el-cascader
              :props="categoryProps"
              v-model="form.categoryIdList"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select
              v-model="form.brandId"
              class="m-2"
              placeholder="选择品牌"
              size="small"
          >
            <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button>取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="CategoryBrand">
import * as categoryBrand from '@/api/product/categoryBrand.js'
import {getBrandAll} from '@/api/product/brand.js'
import {treeSelect} from '@/api/product/category.js'


// ================数据模型定义  start ===============================================
const {proxy} = getCurrentInstance()


// 定义搜索表单数据模型
const brandList = ref([])

//3.查询三级分类数据-搜索 三级分类级联
const props = {
  lazy: true, //懒加载
  value: 'id',
  label: 'name',
  leaf: 'leaf', //获取leaf属性，用于判断是否是叶子节点，叶子节点没孩子，那么不显示 > 箭头
  async lazyLoad(node, resolve) {   // 加载数据的方法
    if (typeof node.value == 'undefined') {
      node.value = 0
    }
    const {data} = await treeSelect(node.value)
    data.forEach(item => {
      //挂载临时属性，用于判断是否为叶子节点。
      item.leaf = !item.hasChildren
    })
    resolve(data)  // 返回数据
  }
};
const categoryProps = ref(props)

// 定义表格数据模型
const categoryBrandList = ref([])

// 分页条数据模型
const total = ref(0)

const data = reactive({
  queryParams: {
    brandId: null,
    categoryId: null,
    pageNum: 1,
    pageSize: 2
  },
  form: {
    categoryIdList: [],  //添加修改选中三个级别的分类id挂到数组上(临时变量作用)。   回显数据时，后端返回id数组挂到当前变量上
    categoryId: null,
    brandId: null
  },
  rules: {
    categoryIdList: [
      {required: true, message: "分类不能为空", trigger: "blur"}
    ],
    brandId: [
      {required: true, message: "品牌不能为空", trigger: "blur"}
    ]
  }
})

const {queryParams, rules, form} = toRefs(data)

const queryCategoryIdList = ref([])

//控制搜索表单是否显示
const showSearch = ref(true)

//添加或修改对话框标题
const title = ref('')

//添加或修改对话框是否显示
const open = ref(false)

//修改和删除按钮共享数据id
const ids = ref([])
//控制修改按钮状态
const single = ref(true)
//控制删除按钮状态
const multiple = ref(true)
// =========   数据模型定义 end===================================================


// ================函数定义  start ===============================================
//1.查询表格数据
// const getList = async ()=>{
//   //const {rows,msg,code} = await categoryBrand.selectCategoryBrand(queryParams.value)
//   //xxx
// }
function getList() {
  categoryBrand.selectCategoryBrand(queryParams.value).then((result) => {
    categoryBrandList.value = result.rows
    total.value = result.total
  })
}

getList()

//2.查询所有品牌数据-搜索 品牌下拉列选
function getBrandAllList() {
  getBrandAll().then((result) => {
    brandList.value = result.data
  })
}

getBrandAllList();

//选中搜索 分类下拉列选数据 会触发change事件，需要将三个级别分类数组的索引为2的三级分类id获取，赋值给queryParams.value.categoryId
function handleCategoryChange() {
  if (queryCategoryIdList.value.length == 3) {
    queryParams.value.categoryId = queryCategoryIdList.value[2]
  }
}

//搜索
function handleQuery() {
  if (queryCategoryIdList.value.length == 3) {
    queryParams.value.categoryId = queryCategoryIdList.value[2]
  }
  getList()
}

//重置搜索表单
function resetQuery() {
  queryParams.value = {
    categoryId: null,
    brandId: null,
    pageNum: 1,
    pageSize: 2
  }
  queryCategoryIdList.value = []
  getList()
}

//弹出添加对话框
function handleAdd() {
  open.value = true
  title.value = "添加"
  resetForm()
}

function resetForm() {
  form.value = {
    categoryId: null
  }
  proxy.resetForm('categoryBrandRef')
}

//添加或修改
function submit() {
  if (form.value.categoryIdList.length == 3) {
    form.value.categoryId = form.value.categoryIdList[2]
  }

  if (form.value.id != null) {
    categoryBrand.updateCategoryBrand(form.value).then(result => {
      open.value = false
      proxy.$modal.msgSuccess(result.msg)
      getList()
    })
  } else {
    categoryBrand.addCategoryBrand(form.value).then(result => {
      open.value = false
      proxy.$modal.msgSuccess(result.msg)
      getList()
    })
  }

}


function handleUpdate(row) {
  open.value = true
  title.value = '修改'
  let _id = row.id || ids.value
  categoryBrand.getCategoryBrandById(_id).then(result => {
    form.value = result.data
  })
}

function selectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = selection.length == 0
}

//删除
function handleDelete(row) {
  let _id = row.id || ids.value
  proxy.$modal.confirm('您确定要删除数据吗?').then(() => {
    return categoryBrand.deleteCategoryBrandById(_id)
  }).then((result) => {
    proxy.$modal.msgSuccess(result.msg)
    getList()
  }).catch((e) => {
    if ('cancel' === e) { //取消删除
      proxy.$modal.msgSuccess('取消删除')
    } else {
      proxy.$modal.msgError('删除失败')
    }
  })
}

// ================函数定义  end ===============================================

</script>